<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 新闻分类
 *
 * @author www.dingwei.cn
 */
class ConsumerFindModel extends MY_Model{

	public $tbFind = 'consumer_find';
    public $tbFindApproval = 'consumer_find_approval';
    public $tbFindCategory = 'consumer_find_category';
    public $tbFindComment = 'consumer_find_comment';
    public $tbUser = 'consumer';

    /**
     * 获取列表数据
     * @return 	array
     * @author heyu
     */
    public function adminPcGetList(){
        $title = trim(get('title'));
        $nickname = trim(get('nickname'));
        $mobile = trim(get('mobile'));
        $name = trim(get('name'));// 类型
        $address = trim(get('address'));
        $status = (int)get('status');
        $send_date_from = strtotime(get('send_date_from'));
        $send_date_to = strtotime(get('send_date_to'));
        if ($title){
            $this->db->like(array('f.title' => $title));
        }
        if ($nickname){
            $this->db->like(array('u.nickname' => $nickname));
        }
        if ($mobile){
            $this->db->like(array('u.mobile' => $mobile));
        }
        if ($name){
            $this->db->like(array('c.name' => $name));
        }
        if ($address){
            $this->db->like(array('f.address' => $address));
        }

        if ($status){
            $this->db->where(array('f.status' => $status));
        }
        if($send_date_from){
            $this->db->where('f.addtime >=', $send_date_from);
        }
        if($send_date_to){
            $this->db->where('f.addtime <= ', strtotime('+1day', $send_date_to));
        }
        $this->db->select('u.nickname,u.mobile,c.name,f.id,f.title,f.content,f.province,f.city,f.county,f.address,f.latitude,
            f.longitude,f.read_number,f.status,f.addtime')
            ->join($this->tbFindCategory.' c', 'c.id=f.category_id')
            ->join($this->tbUser.' u', 'u.id=f.consumer_id', 'left')
            ->order_by('f.id desc');

        $data = $this->pagination($this->tbFind.' f');
        if (!empty($data['data'])) {
            $ids = array();
            foreach ($data['data'] as $k => $v) {
                if (!in_array($v['province'], $ids)) {
                    $ids[] = $v['province'];
                }
                if (!in_array($v['city'], $ids)) {
                    $ids[] = $v['city'];
                }
                if (!in_array($v['county'], $ids)) {
                    $ids[] = $v['county'];
                }
            }
            get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $region = $this->mSetting->getLocationNameByIds($ids);

            foreach ($data['data'] as $kk => $vv) {
                $data['data'][$kk]['title'] = base64_decode($vv['title']);
                $data['data'][$kk]['content'] = base64_decode($vv['content']);
                $data['data'][$kk]['province_name'] = $region[$vv['province']]['name'];
                $data['data'][$kk]['city_name'] = $region[$vv['city']]['name'];
                $data['data'][$kk]['county_name'] = $region[$vv['county']]['name'];
                $data['data'][$kk]['region'] = $region[$vv['province']]['name'].'-'.$region[$vv['city']]['name'].
                    '-'.$region[$vv['county']]['name'];
            }
        }
        return $data;
    }

    /**
     * 获取发现列表
     * @param int   $county         区域id
     * @param int   $sort           排序id
     * @param int   $page           分页
     * @param int   $limit          每页显示多少条
     * @param array $ids            通过ids获取信息[收藏使用]
     * @param int   $latitude
     * @param int   $longitude
     * @param int   $categoryId
     * @return mixed
     * @author zyl
     */
    public function appGetList($county = 0, $sort = 0, $page = 1 , $limit = 0, $ids = array(),$latitude = 0,
                               $longitude = 0,$categoryId = 0){
    	
    	$sortType = array(
    			1 => 'distance asc', //距离最近
    			2 => 'addtime desc', //时间最新
    			3 => 'read_number desc', //浏览最高
    	);
    	
    	//ids检索
    	if ($ids){
    		$this->db->where_in('f.id',$ids);
    	}
    	
    	//分类
    	if ($categoryId){
    		$this->db->where_in('f.category_id',$categoryId);
    	}
    	
    	//区域
    	if ($county){
    		$this->db->where('f.county',$county);
    	}
    	
    	//区域检索
    	if(array_key_exists($sort, $sortType)){
    		$this->db->order_by($sortType[$sort]);
    	}
    	
    	//距离的Sql
    	$distance = ', 10000 as distance';
    	if ($latitude && $longitude){
    		$distance = ',if(f.longitude > 0 and  f.latitude, ( ACOS(SIN(('.$latitude.' * 3.1415) / 180 ) *SIN((f.latitude * 3.1415) / 180 )
    			+ COS((' .$latitude.' * 3.1415) / 180 ) * COS((f.latitude * 3.1415) / 180 ) * COS((' .$longitude.
    			' * 3.1415) / 180 - (f.longitude * 3.1415) / 180 ) ) * 6380 ), 10000000) as distance';
    	}
    	
    	$this->db->select('f.id,f.title,f.read_number,f.consumer_id,c.name as category_name,
							f.content,f.province,f.city,f.county,f.county_name,f.address,f.addtime'.$distance)
		->where('f.is_delete',1)
		->where('f.status',2)
    	->join($this->tbFindCategory.' c','f.category_id = c.id','left');
    	
    	$tA = $this->appPage($this->tbFind.' f', $page,false,$limit);
    	
    	//数据
    	$tLocationIds = array();
    	$tConsumerIds = array();
    	
    	foreach ($tA['list'] as $k=>$v){
    		if (!in_array($v['province'], $tLocationIds)){
    			$tLocationIds[] = $v['province'];
    		}
    		if (!in_array($v['city'], $tLocationIds)){
    			$tLocationIds[] = $v['city'];
    		}
    		if (!in_array($v['county'], $tLocationIds)){
    			$tLocationIds[] = $v['county'];
    		}
    		$tA['list'][$k]['addtime'] = showBeautifulTimeForMat($v['addtime']);
    		//$tA['list'][$k]['address'] = '';//地址默认
    		
    		if ( ! in_array($v['consumer_id'], $tConsumerIds)){
    			$tConsumerIds[] = $v['consumer_id'];
    		}
    	}
    	
    	
    	//组合地址
    	if ($tLocationIds){
    		get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
    		$tLocation = $this->mSetting->getLocationNameByIds($tLocationIds);
    	}
    	
    	//获取发布人头像 名字
    	$tConsumer = array();
    	if ($tConsumerIds){
    		get_instance()->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
    		$tConsumer = $this->mConsumer->getInfoByIds($tConsumerIds);
    	}

    	
    	foreach ($tA['list'] as $k=>$v){
    		if ($tLocation){
// 	    		$tA['list'][$k]['address'] = $tLocation[$v['province']]['name'].
// 	    		$tLocation[$v['city']]['name'].
// 	    		$tLocation[$v['county']]['name'].
// 	    		$v['address'];
// 	    		unset($tA['list'][$k]['province']);
// 	    		unset($tA['list'][$k]['city']);
// 	    		unset($tA['list'][$k]['county']);
    		}
            $tA['list'][$k]['title'] = base64_decode($v['title']);
            $tA['list'][$k]['content'] = base64_decode($v['content']);
    		$tA['list'][$k]['nickname'] = '';
    		$tA['list'][$k]['portrait'] = '';
    		
    		if ($tConsumer){
    			$tA['list'][$k]['nickname'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['nickname'] : '暂无昵称';
    			$tA['list'][$k]['portrait'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['portrait']['xs'] : '';
    		}
    	}
    	
	    return $tA['list'];
    }

    /**
     * 
     * @param number $page
     * @return array|array[]|number[]|unknown[]
     */
    public function appGetCommentList($findId,$page = 1,$limit = 0){
    	
    	$this->db
    	->select('c.id,c.content,c.addtime,c.parent_id,u.portrait,u.nickname,if(c.parent_id = 0, c.id, c.parent_id) as sort')
    	->join($this->tbUser.' u','u.id = c.consumer_id','left')
        ->order_by('max_parent_id desc,c.parent_id asc,c.addtime asc')
//        ->order_by('c.parent_id asc,c.addtime asc')
    	->where('c.find_id',$findId);
    	
    	$tA = $this->appPage($this->tbFindComment.' c', $page,false,$limit);
    	if ( ! $tA['list']){
    		return array();
    	}
    	$tData = array();
    	foreach ($tA['list'] as $k=>$v){
    		$tData[$v['id']] = $v;
    	}
    	
    	foreach ($tA['list'] as $k=>$v){
    		$tA['list'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
    		$tA['list'][$k]['content'] = base64_decode($v['content']);
    		$tA['list'][$k]['portrait'] = getImage($v['portrait'],'xs');
    		if ($v['parent_id'] > 0){
    		    $nickname = '暂无昵称';
            }else{
                $nickname = '';
            }
    		$tA['list'][$k]['parent_name'] = empty($tData[$v['parent_id']]['nickname'])?$nickname:$tData[$v['parent_id']]['nickname'];
    	}

    	return $tA['list'];
    }
    
    /**
     * 保存发现评论
     * @param array     $data
     * @param integer   $commentId
     * @return boolean|boolean|number
     * @author zyl
     */
    public function saveComment($data,$commentId = 0){
    	if ($commentId){
    		$this->db->where('id',$commentId);
    		$query = $this->update($this->tbFindComment, $data);
    		return $query === false ? false : true;
    	}else{
    		return $this->insert($this->tbFindComment, $data);
    	}
    }

    /**
     * 获取分类下发现帖子总数
     * @param number $categoryId 分类id
     * @return array 
     * @author zyl
     */
    public function getFindCategoryTotal($categoryId = 0){
    	if ($categoryId){
    		$this->db->where('category_id',$categoryId);
    	}
    	return $this->count($this->tbFind);
    }
    
    /**
     * 获取我的发布列表
     * @param integer $consumerId 消费者id
     * @param number $page 分页
     * @return array|number|unknown
     * @author zyl
     */
    public function appGetMyList($consumerId,$page = 1){
    	
    	$this->db->select('f.id,f.title,f.category_id,f.pic,f.county_name,f.content,fc.name as category_name,f.province,
							f.read_number,f.city,f.county,f.address,f.latitude,f.longitude,f.addtime,f.nickname,f.mobile')
    	->join($this->tbFindCategory.' fc','fc.id = f.category_id','left')
    	->where('f.is_delete',1)
        ->order_by('f.addtime desc')
    	->where('f.consumer_id',$consumerId);
    	$tA = $this->appPage($this->tbFind.' f', $page, true);
    	
    	$locationIds = array(); 
    	foreach ($tA['list'] as $k=>$v){
    		if (!in_array($v['province'], $locationIds)){
    			$locationIds[] = $v['province'];
    		}
    		if (!in_array($v['city'], $locationIds)){
    			$locationIds[] = $v['city'];
    		}
    		if (!in_array($v['county'], $locationIds)){
    			$locationIds[] = $v['county'];
    		}
    	}
    	
    	/**
    	 * 获取地址
    	 */
    	$tLocation = array();
    	if ($locationIds){
	    	get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
	    	$tLocation = $this->mSetting->getLocationNameByIds($locationIds);
    	}
    	
    	/**
    	 * 处理地址
    	 */
    	//获取特殊值
    	get_instance()->loadModel('ConsumerFindAttributeModel', 'mAttribute','consumer');
    	foreach ($tA['list'] as $k=>$v){
            $tA['list'][$k]['title'] = base64_decode($v['title']);
            $tA['list'][$k]['content'] = base64_decode($v['content']);
    		$tA['list'][$k]['addtime'] = showBeautifulTimeForMat($v['addtime']);
//     		$tA['list'][$k]['address'] = isset($tLocation[$v['province']])?$tLocation[$v['province']]['name']:'';
//     		$tA['list'][$k]['address'] .= isset($tLocation[$v['city']])?$tLocation[$v['city']]['name']:'';
//     		$tA['list'][$k]['address'] .= isset($tLocation[$v['county']])?$tLocation[$v['county']]['name']:'';
//     		$tA['list'][$k]['address'] .= $v['address'];
    		
    		$pic = json_decode($v['pic'],true);
    		$tA['list'][$k]['pic'] = array();
    		if (!empty($pic)) {
                foreach ($pic as $kk => $vv) {
                    $tA['list'][$k]['pic'][] = getImage($vv, 'og');
                }
            }
    		$tA['list'][$k]['attr'] = $this->mAttribute->getAttributeValueList($v['id']);
/*     		unset($tA['list'][$k]['province']);
    		unset($tA['list'][$k]['city']);
    		unset($tA['list'][$k]['county']); */
    	}
    	
    	return $tA;
    }
    
    /**
     * 获取信息详情
     * @param $id
     * @param $mini     bool        true：少量数据
     * @return array
     * @author heyu zyl
     */
    public function getInfo($id, $mini = false){
        if (!$id){
            return array();
        }
        if ($mini){
            $this->db->select('id,consumer_id,category_id,title,status,pic')
                ->where(array('id' => $id));
            $tA = $this->getOne($this->tbFind);
            return $tA;
        }

        $this->db->select('f.id,f.title,f.consumer_id,f.approval,f.category_id,f.content,f.pic,f.province,f.city,f.county,f.county_name,f.address,f.address as address_name,f.latitude,f.longitude,
            f.read_number,f.status,f.addtime,f.nickname,f.mobile,u.portrait,c.name')
            ->join($this->tbUser.' u', 'f.consumer_id=u.id', 'left')
            ->join($this->tbFindCategory.' c', 'f.category_id=c.id')
            ->where(array('f.id' => $id));
        $tA = $this->getOne($this->tbFind.' f');
        if (!empty($tA)) {
            $imgArr = json_decode($tA['pic'], true);
            if (!empty($imgArr)) {
                foreach ($imgArr as $k => $v) {
                    $imgArr[$k] = getImage($v, 'og');
                }
            }
            $tA['title'] = base64_decode($tA['title']);
            $tA['content'] = base64_decode($tA['content']);
            $tA['pic'] = $imgArr;
            $tA['addtime'] = dateFormat($tA['addtime'], true);
            $tA['portrait'] = isset($tA['portrait']) ? base_url($tA['portrait']) : getDefaultPortrait();
            get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $region = $this->mSetting->getLocationNameByIds(array($tA['province'], $tA['city'], $tA['county']));
            $tA['region'] = $region[$tA['province']]['name'] . '-' . $region[$tA['city']]['name'] . '-' . $region[$tA['county']]['name'];
            $tA['address'] = $region[$tA['province']]['name'] . $region[$tA['city']]['name'] . $region[$tA['county']]['name'] . $tA['address'];
            $tA['approval'] = empty($tA['approval'])?"0":$tA['approval'];
        }
        return $tA;
	}

    /**
     * 获取发现评论信息
     * @param $commentId
     * @autor zyl
     */
	public function getCommentInfo($commentId){

        $this->db
            ->select('id,parent_id,find_id,max_parent_id')
            ->where('id',$commentId);
        $tA = $this->getOne($this->tbFindComment);
        return $tA;
    }

    /**
	 * 是否点赞是否浏览
     * @param $findId       int
     * @param $consumerId   int
	 * @param $type         int     1-是否点赞 2-浏览
     * @return int
	 * @author zyl
	 */
	public function hasApproval($findId,$consumerId,$type = 1){
		
		$this->db->where(array('find_id'=>$findId,'consumer_id'=>$consumerId));
		$tA = $this->getOne($this->tbFindApproval);

		if ( ! $tA){
			//没有点赞
			return false;
		}
		
		if ($type == 1){
			return ! empty($tA['is_approval']);
		}elseif ($type == 2){
			return ! empty($tA['is_view']);
		}
	}
	/*public function hasApproval($findId,$consumerId,$type = 1){

		$this->db->where(array('find_id'=>$findId,'consumer_id'=>$consumerId));
		$tA = $this->getOne($this->tbFindApproval);

		if (empty($tA)){
			//没有点赞
			return 0;
		}

		if ($type == 1){
			return $tA['is_approval'] == 2 ? 2 : 1;
		}elseif ($type == 2){
			return $tA['is_view'] == 2 ? 2 : 1;
		}
	}*/

	/**
	 * 获取用户最近发布的总数
	 * @param integer $consumerId 用户id
     * @return array
	 * @author zyl
	 */
	public function getFindTotal($consumerId){
	    $this->db->where('consumer_id',$consumerId)
            ->where('is_delete != 2');
	    return $this->count($this->tbFind);
	}
	
	/**
	 * 保存信息
	 * @param 	array 	$data
	 * @param   integer $id
	 * @return	boolean|integer
	 * @author heyu
	 */
	public function save($data, $id = 0){
	    if($id){
	        $this->db->where('id', $id);
	        return $this->update($this->tbFind, $data);
	    }
	
	    return $this->insert($this->tbFind, $data);
	}
	
	/**
	 * 保存信息
	 * @param 	array 	$data
	 * @param  integer $findId
	 * @param  integer $consumerId
	 * @return	boolean|integer
	 * @author heyu
	 */
	public function saveApproval($data, $findId = 0,$consumerId = 0){
		if($findId && $consumerId){
	    	$this->db->where('find_id', $findId);
	    	$this->db->where('consumer_id', $consumerId);
	        return $this->update($this->tbFindApproval, $data);
	    }
	
	    return $this->insert($this->tbFindApproval, $data);
	}

    /**
     * 删除
     * @param $id
     * @return bool
     * @author heyu
     */
    public function deleteFind($id){
        if (!$id){
            return false;
        }
        $this->db->where(array('id' => $id));
        return $this->delete($this->tbFind);
    }

    /**
     * 删除
     * @param $findId
     * @return bool
     * @author heyu
     */
    public function deleteApproval($findId){
        if (!$findId){
            return false;
        }
        $this->db->where(array('find_id' => $findId));
        return $this->delete($this->tbFindApproval);
    }
    /**
     * 查看分类下的信息
     * @param $id       int         分类id
     * @return array
     * @author heyu
     */
    public function getFindByNewsCategory($id){
        if (!$id){
            return array();
        }
        $this->db->select('id')
            ->where(array('category_id' => $id));
        $tA = $this->getAll($this->tbFind);
        return $tA;
    }
}